/**
 * @Project Name :  als-rpc
 * @Package Name :  com.alvis.transfer
 * @Description :  TODO
 * @author :  Alvis
 * @Creation Date:  2018-07-03 10:29 AM
 * @ModificationHistory Who    When    What
 * --------  ---------  --------------------------
 */
package com.alvis.transfer;

import com.alvis.config.RpcConfig;
import com.alvis.utilities.Component;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author :  Alvis
 * @Description :  TODO
 * @Creation Date:  2018-07-03 10:29 AM
 */
public class RpcServer implements Component {
    private final static Logger logger = LoggerFactory.getLogger(RpcServer.class);

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    @Override
    public void start() {

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ServerChannelHandler())
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            logger.info("rcp server is receiving client ... ");
            ChannelFuture f = serverBootstrap.bind(RpcConfig.getPort()).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            logger.error(e.toString());
        }
    }

    @Override
    public void stop() {
        try {
            workerGroup.shutdownGracefully().sync();
            bossGroup.shutdownGracefully().sync();
        } catch (InterruptedException e) {
            logger.error(e.toString());
        }
    }
}
